var postData = require("../../../data/post-data.js")
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    postData: null,
    collected: false,
    isPlayMusic: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var postId = options.postId;
    this.data.currId = postId;
    this.setData({
      postData: postData.postList[postId]
    });

    var postsCollected = wx.getStorageSync("postsCollected");
    if (postsCollected) {
      var postCollected = postsCollected[postId];
      this.setData({
        collected: postCollected
      });
    } else {
      var postsCollected = [];
      postsCollected[postId] = false;
      wx.setStorageSync("postsCollected", postsCollected);
    }
    if (app.globalData.g_isPlayingMusic && app.globalData.g_musicPostId == this.data.currId) {
      this.setData({
        isPlayMusic: true
      })
    }
    this.setMusicMonitor();

  },
  setMusicMonitor: function() {
    var that = this;
    wx.onBackgroundAudioPlay(function() {
      that.setData({
        isPlayMusic: true
      })
      app.globalData.g_isPlayingMusic = true;
      app.globalData.g_musicPostId = that.data.currId;
    });

    wx.onBackgroundAudioPause(function() {
      that.setData({
        isPlayMusic: false
      })
      app.globalData.g_isPlayingMusic = false;
      app.globalData.g_musicPostId = that.data.null;
    })
  },

  onCollectiontap: function(event) {
    var postsCollected = wx.getStorageSync("postsCollected");
    var postCollected = postsCollected[this.data.currId];
    postCollected = !postCollected;
    postsCollected[this.data.currId] = postCollected;
    wx.setStorageSync("postsCollected", postsCollected);
    this.setData({
      collected: postCollected
    });

    wx.showToast({
      title: postCollected ? '收藏成功' : '取消成功',
    })



  },

  onMusicTap: function(event) {
    var isPlayMusic = this.data.isPlayMusic;
    var cId = this.data.currId;
    console.log(postData);
    if (isPlayMusic) {
      wx.pauseBackgroundAudio();
      this.setData({
        isPlayMusic: false
      });
    } else {
      wx.playBackgroundAudio({
        dataUrl: postData.postList[cId].music.url,
        title: postData.postList[cId].music.title,
        coverImgUrl: postData.postList[cId].music.coverImg
      })
      this.setData({
        isPlayMusic: true
      });
    }
  },

  onFxTap: function(event) {
    console.log(event);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})